#include "gltexture.h"
#include "core/spectrum.h"
#include <gl\glut.h>

GLTexture::~GLTexture() {
	SAFE_DELETE_ARRAY(data);
}
GLTexture::GLTexture() {
	filename[0] = '\0';
	data = NULL;
	width = height = 0;
	enable = false;
}

GLTexture::GLTexture(char *file) {
	strcpy(filename, file);
	data = NULL;
	width = height = 0;
	LoadTexture();
	enable = false;
}

void GLTexture::SetTexture(char *file) {
	strcpy(filename, file);
	LoadTexture();
	enable = false;
}

void GLTexture::LoadTexture() {
	SAFE_DELETE_ARRAY(data);
	Spectrum *tex = ReadImage(filename, &width, &height);
	if(tex) {
		Debug("%s was load with width = %d and height = %d\n", filename, width, height);
		data = new unsigned char[width * height * 3];
		for(int i = 0; i < width * height; i++)
			tex[i].ToRGB(&data[3*i]);
	}
	SAFE_DELETE_ARRAY(tex);
}

void GLTexture::Enable() {
	
	if(!enable) {
		glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
		//glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
		gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data);
		enable = true;
	}

	glEnable(GL_TEXTURE_2D);
}

void GLTexture::Disable() {
	glDisable(GL_TEXTURE_2D);
}